import 'package:bloc_pattern/bloc_pattern.dart';
import 'package:flutter/material.dart';

import 'bloc/cart_list_bloc.dart';
import 'model/food_item.dart';

class Cart extends StatelessWidget {
  final CartListBlocController cartListBlocController =
      BlocProvider.getBloc<CartListBlocController>();

  @override
  Widget build(BuildContext context) {
    List<FoodItem> foodItems;

    return StreamBuilder(
      stream: cartListBlocController.outListStream,
      builder: (context, snapshot) {
        if (snapshot.data != null) {
          foodItems = snapshot.data;
          return Scaffold(
            body: SafeArea(
              child: Container(
                child: CartBody(foodItems: foodItems),
              ),
            ),
            bottomNavigationBar: BottomBar(foodItems: foodItems),
          );
        } else {
          return Scaffold(
            body: Empty(),
          );
        }
      },
    );
  }
}

class BottomBar extends StatelessWidget {
  List<FoodItem> foodItems;
  BottomBar({this.foodItems});
  Widget totalAmount(List<FoodItem> foodItems) {
    return Container(
      margin: EdgeInsets.only(right: 10),
      padding: EdgeInsets.all(25),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "Total",
            style: TextStyle(fontSize: 25, fontWeight: FontWeight.w300),
          ),
          Text("\$${returnTotalAmount(foodItems)}")
        ],
      ),
    );
  }

  double returnTotalAmount(List<FoodItem> foodItems) {
    double total = 0;
    if (foodItems.length > 0) {
      for (var item in foodItems) {
        total += item.quantity * item.price;
      }
      return total;
    } else {
      return 0;
    }
  }

  Widget persons() {
    return Container(
      margin: EdgeInsets.only(right: 10),
      padding: EdgeInsets.symmetric(vertical: 30),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            'Persons',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700),
          ),
          CustomPersonWidget()
        ],
      ),
    );
  }

  Widget nextButtonBar() {
    return Container(
      margin: EdgeInsets.only(right: 25),
      padding: EdgeInsets.all(25),
      decoration: BoxDecoration(
        color: Color(0xfffeb324),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "15-25 min",
            style: TextStyle(fontWeight: FontWeight.w800, fontSize: 14),
          ),
          Text(
            "Next",
            style: TextStyle(fontWeight: FontWeight.w900, fontSize: 16),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 35, bottom: 25),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          totalAmount(foodItems),
          Divider(
            height: 1,
            color: Colors.grey[700],
          ),
          persons(),
          nextButtonBar(),
        ],
      ),
    );
  }
}

class Empty extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('空空如野'),
    );
  }
}

class CustomPersonWidget extends StatefulWidget {
  @override
  _CustomPersonWidgetState createState() => _CustomPersonWidgetState();
}

class _CustomPersonWidgetState extends State<CustomPersonWidget> {
  int noOfPersons = 1;
  double _buttonWidth = 30;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(right: 25),
      decoration: BoxDecoration(
          border: Border.all(color: Colors.grey[300], width: 2),
          borderRadius: BorderRadius.circular(10)),
      padding: EdgeInsets.symmetric(vertical: 5),
      width: 120,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          SizedBox(
            width: _buttonWidth,
            height: _buttonWidth,
            child: FlatButton(
                onPressed: () {
                  setState(() {
                    if (noOfPersons > 1) {
                      noOfPersons--;
                    }
                  });
                },
                child: Text(
                  "-",
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),
                )),
          ),
          Text(
            noOfPersons.toString(),
            style: TextStyle(
              fontWeight: FontWeight.w700,
            ),
          ),
          SizedBox(
            width: _buttonWidth,
            height: _buttonWidth,
            child: FlatButton(
                onPressed: () {
                  setState(() {
                    noOfPersons++;
                  });
                },
                child: Text(
                  "+",
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),
                )),
          ),
        ],
      ),
    );
  }
}

class CartBody extends StatelessWidget {
  List<FoodItem> foodItems;
  CartBody({this.foodItems});
  Widget title() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 35),
      child: Row(
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "My",
                style: TextStyle(fontWeight: FontWeight.w700, fontSize: 35),
              ),
              Text(
                "Order",
                style: TextStyle(fontWeight: FontWeight.w300, fontSize: 35),
              )
            ],
          )
        ],
      ),
    );
  }

  Widget foodItemList() {
    return ListView.builder(
        itemCount: foodItems.length,
        itemBuilder: (context, index) {
          return CartListItem(foodItem: foodItems[index]);
        });
  }

  Widget noItemContainer() {
    return Container(
      child: Center(
        child: Text(
          "No more items left in the cart",
          style: TextStyle(
              color: Colors.grey[500],
              fontSize: 30,
              fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(35, 40, 25, 0),
      child: Column(
        children: <Widget>[
          CustomAppBar(),
          title(),
          Expanded(
            flex: 1,
            child: foodItems.length > 0 ? foodItemList() : noItemContainer(),
          )
        ],
      ),
    );
  }
}

class CartListItem extends StatelessWidget {
  final FoodItem foodItem;
  CartListItem({this.foodItem});

  @override
  Widget build(BuildContext context) {
    return Draggable(
      child: Container(
        margin: EdgeInsets.only(bottom: 25),
        child: ItemContent(foodItem: foodItem),
      ),
      onDragStarted: () {
        //删除当前项print("onDragStarted");
      },
      onDragEnd:(details){
        print("------");
      },
      onDraggableCanceled:(velocity,offset){
        print('onDraggableCanceled:(${offset.dx}-${offset.dy})');
      },
      data: this.foodItem,
      feedback: Container(
        margin: EdgeInsets.only(bottom: 25),
        child: DraggableItemContent(foodItem: foodItem),
      ),
    );
  }
}

class DraggableItemContent extends StatelessWidget {
  final FoodItem foodItem;
  DraggableItemContent({this.foodItem});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Image.network(
              foodItem.imgUrl,
              fit: BoxFit.fill,
              height: 55,
              width: 80,
            ),
          ),
          RichText(
            text: TextSpan(
                style: TextStyle(
                  fontWeight: FontWeight.w700,
                  color: Colors.grey,
                  fontSize: 16,
                ),
                children: [
                  TextSpan(text: foodItem.quantity.toString()),
                  TextSpan(text: " x "),
                  TextSpan(text: foodItem.title)
                ]),
          )
        ],
      ),
    );
  }
}

class ItemContent extends StatelessWidget {
  final FoodItem foodItem;
  ItemContent({this.foodItem});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Image.network(
              foodItem.imgUrl,
              fit: BoxFit.fill,
              height: 55,
              width: 80,
            ),
          ),
          RichText(
            text: TextSpan(
                style: TextStyle(
                  fontWeight: FontWeight.w700,
                  color: Colors.black,
                  fontSize: 16,
                ),
                children: [
                  TextSpan(text: foodItem.quantity.toString()),
                  TextSpan(text: " x "),
                  TextSpan(text: foodItem.title)
                ]),
          ),
          Text("\$${foodItem.quantity * foodItem.price}")
        ],
      ),
    );
  }
}

class CustomAppBar extends StatefulWidget {
  @override
  _CustomAppBarState createState() => _CustomAppBarState();
}

class _CustomAppBarState extends State<CustomAppBar> {
  final CartListBlocController _cartListBlocController =
      BlocProvider.getBloc<CartListBlocController>();

  @override
  Widget build(BuildContext context) {
    bool isOver = false;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Padding(
          padding: EdgeInsets.all(5),
          child: GestureDetector(
            child: Icon(
              Icons.arrow_back,
              size: 30,
            ),
            onTap: () {
              Navigator.pop(context);
            },
          ),
        ),
        DragTarget<FoodItem>(
          onWillAccept: (data) {
            setState(() {
              isOver = true;
            });
            return data != null;
          },
          onAccept: (data) {
            _cartListBlocController.removeFromList(data);
          },
          onLeave: (data) {
            setState(() {
              isOver = false;
            });
            print("onLeave");
          },
          builder: (context, data, rejectData) {
            return GestureDetector(
              child: Padding(
                padding: EdgeInsets.all(5.0),
                child: Icon(Icons.delete ,color: isOver?Colors.red:Colors.black,)
              ),
            );
          },
        )
      ],
    );
  }
}
